package com.service.productType;

import com.domain.HttpResponse;
import com.domain.ex.Codes;
import com.mapper.self.ProductTypeMapper;
import com.pojo.ShProductType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2016/7/20.
 */
@Service
public class ProductTypeServiceImpl implements ProductTypeService {

  @Autowired
  private ProductTypeMapper productTypeMapper;


  @Override
  public Object saveOrUpdate(Integer id, String name, String remark) {
    int count = productTypeMapper.queryByName(name.trim());
    if (count > 0){
      return HttpResponse.create(Codes.SystemDeclare,"该类别名称已经存在");
    }
    ShProductType productType = new ShProductType();
    productType.setId(id);
    productType.setName(name);
    productType.setRemark(remark);
    Date now = new Date();
    productType.setCreateTime(now);
    productType.setUpdateTime(now);
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String email = request.getSession().getAttribute("email").toString();
    productType.setEmail(email);
    productTypeMapper.saveOrUpdate(productType);
    return HttpResponse.OK();
  }

  @Override
  public List<ShProductType> list(String email, Integer pageNo, Integer pageSize) {
    if (pageNo == null){
      pageNo = 1;
    }
    if (pageSize == null){
      pageSize = 100;
    }
    if (pageNo != null && pageNo > 0) {
      pageNo -= 1;
    }
    return productTypeMapper.list(email, pageSize, pageNo * pageSize);
  }


  @Override
  public Object del(Integer id) {

    int typeInUsing = productTypeMapper.isTypeInUsing(id);
    if (typeInUsing > 0){
      return HttpResponse.create(Codes.SystemDeclare,"该分类正在使用中,不可删除");
    }
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String email = request.getSession().getAttribute("email").toString();
    productTypeMapper.del(id, email);
    return HttpResponse.OK();
  }
}
